<template>
  <!-- v-charts  k线 -->
  <div class="charts-box" @mousedown="down" @mouseup="up">
    <!-- {{Topic}} -->
    <!-- echarts版本 -->
    <div
      id="echartContainer"
      v-loading="loading"
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      style="width:100%; height:500px"
      ref="echartContainer"
    ></div>
    <div class="k-box pos-box">
      <p>
        开=
        <span :style="'color:'+datas.color">{{datas.open.value}}</span>
        &nbsp;
        高=
        <span :style="'color:'+datas.color">{{datas.heigh.value}}</span>
        &nbsp;
        收=
        <span :style="'color:'+datas.color">{{datas.low.value}}</span>
        &nbsp;
        低=
        <span :style="'color:'+datas.color">{{datas.close.value}}</span>&nbsp;
      </p>
      <div class="ma-box pos-box">
        MA5：
        <span :style="'color:'+ma.ma5.color">{{ma.ma5.value}}</span>
        <br />MA10：
        <span :style="'color:'+ma.ma10.color">{{ma.ma10.value}}</span>
        <br />MA30：
        <span :style="'color:'+ma.ma30.color">{{ma.ma30.value}}</span>
        <br />MA60：
        <span :style="'color:'+ma.ma60.color">{{ma.ma60.value}}</span>
        <br />
      </div>
    </div>
    <div class="vol-box pos-box">
      <p>
        成交量：
        <span :style="'color:'+vol.color">{{vol.value}}</span>
      </p>
    </div>
    <div class="macd-box pos-box">
      <p>
        MACD：
        <span :style="'color:'+macd.macd.color">{{macd.macd.value}}</span>&nbsp;
        DIF：
        <span :style="'color:'+macd.dif.color">{{macd.dif.value}}</span>&nbsp;
        DEA：
        <span :style="'color:'+macd.dea.color">{{macd.dea.value}}</span>&nbsp;
      </p>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
var echarts = require("echarts");
var charts = "";
export default {
  data() {
    return {
      topic: "",
      // k所有数据存储
      mapData: [],
      loading: false,
      kData: {
        datas: [], //array
        times: [], //array
        vols: [], //int
        macds: [], //int
        difs: [], //int
        deas: [] //int
      },
      Chart: "",
      //数据模型 time0 open1 close2 min3 max4 vol5 tag6 macd7 dif8 dea9
      ChartData: [],
      // 数据开始时间
      startTime: "",
      startLeft: null,
      startDown: false,
      isReq: true,
      // 窗口显示最大数据百分比
      minData: 5,
      maxData: 80,
      // 提示框的数据显示
      macd: {
        macd: {
          name: "macd",
          value: 0,
          color: ""
        },
        dif: {
          name: "dif",
          value: 0,
          color: ""
        },
        dea: {
          name: "dea",
          value: 0,
          color: ""
        }
      },
      datas: {
        color: "",
        open: {
          name: "开",
          value: 0
        },
        close: {
          name: "收",
          value: 0
        },
        low: {
          name: "低",
          value: 0
        },
        heigh: {
          name: "高",
          value: 0
        }
      },
      ma: {
        ma5: {
          name: "MA5",
          value: 0,
          color: ""
        },
        ma10: {
          name: "MA10",
          value: 0,
          color: ""
        },
        ma30: {
          name: "MA30",
          value: 0,
          color: ""
        },
        ma60: {
          name: "MA60",
          value: 0,
          color: ""
        }
      },
      vol: {
        name: "成交量",
        value: 0,
        color: ""
      },
      choise: "km"
    };
  },

  methods: {
    // 页面初始创建一个空的k线图
    createChart() {
      console.log("k初始化");
      let _this = this;
      charts = echarts.init(this.$refs.echartContainer);
      // 配置项
      charts.setOption({
        // 鼠标悬浮框的样式设置
        tooltip: {
          trigger: "axis",
          showContent: true,
          axisPointer: {
            type: "cross"
          },
          backgroundColor: "rgba(19, 22, 37,0.001)",
          formatter: function(params) {
            _this.dealTool(params);
          }
        },
        axisPointer: {
          // 多图联动这里实现
          link: { xAxisIndex: "all" }
        },
        grid: [
          {
            height: "70%",
            x: 5,
            y: 5,
            x2: 80,
            y2: 0
          },
          {
            left: 5,
            right: 80,
            top: "76%",
            height: "10%"
          },
          {
            left: 5,
            right: 80,
            top: "85%",
            height: "14%"
          }
        ],
        xAxis: [
          {
            data: [],
            type: "category",
            scale: true,
            boundaryGap: false,
            axisLine: { onZero: false },
            //网格样式
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#222736"],
                width: 1,
                type: "solid"
              }
            },
            splitNumber: 20,
            min: "dataMin",
            max: "dataMax"
          },
          {
            data: [],
            type: "category",
            gridIndex: 1,
            axisLabel: { show: false },
            boundaryGap: false,
            axisPointer: {
              label: {
                show: false
              }
            }
          },
          {
            data: [],
            type: "category",
            gridIndex: 2,
            axisLabel: { show: false },
            boundaryGap: false,
            axisPointer: {
              label: {
                show: false
              }
            }
          }
        ],
        yAxis: [
          {
            scale: true,
            splitArea: {
              show: false
            },
            //网格样式
            splitLine: {
              show: true,
              lineStyle: {
                color: ["#222736"],
                width: 1,
                type: "solid"
              }
            },
            axisLabel: {
              color: "#C7CEE0"
            },
            position: "right"
          },
          {
            splitArea: {
              show: false
            },
            position: "right",
            scale: true,
            gridIndex: 1,
            splitNumber: 3,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false }
          },
          {
            splitArea: {
              show: false
            },
            position: "right",
            scale: true,
            gridIndex: 2,
            splitNumber: 4,
            axisLine: { onZero: false },
            axisTick: { show: false },
            splitLine: { show: false },
            axisLabel: { show: false }
          }
        ],
        dataZoom: {
          show: false,
          filterMode: "filter",
          type: "inside",
          xAxisIndex: [0, 1, 2],
          start: 80,
          end: 100,
          // 限制窗口的最小值，窗口显示的最少数据
          height: 0,
          throttle: 100 //设置触发视图刷新的频率。单位为毫秒（ms）
        },
        series: [
          {
            name: this.choise,
            type: "candlestick",
            data: [],
            barMaxWidth: 15,
            itemStyle: {
              normal: {
                color: "#12b886",
                color0: "#fa5252",
                borderColor: "#12b886",
                borderColor0: "#fa5252"
              }
            },
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          },
          {
            name: "MA5",
            type: "line",
            symbol: "none",
            data: [],
            color: "#19D4AE",
            smooth: true,
            lineStyle: {
              normal: {
                opacity: 0.5
              }
            },
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          },
          {
            name: "MA10",
            type: "line",
            symbol: "none",
            color: "#5AB1EF",
            data: [],
            smooth: true,
            lineStyle: {
              normal: {
                opacity: 0.5
              }
            },
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          },
          {
            name: "MA30",
            type: "line",
            symbol: "none",
            color: "#FA6E86",
            data: [],
            smooth: true,
            lineStyle: {
              normal: {
                opacity: 0.5
              }
            },
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          },
          {
            name: "MA60",
            type: "line",
            symbol: "none",
            color: "#FFB980",
            data: [],
            smooth: true,
            lineStyle: {
              normal: {
                opacity: 0.5
              }
            },
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          },
          {
            name: "Volumn",
            type: "bar",
            xAxisIndex: 1,
            yAxisIndex: 1,
            data: [],
            barMaxWidth: 15
          },
          {
            name: "MACD",
            type: "bar",
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: [],
            barMaxWidth: 15
          },
          {
            name: "DIF",
            type: "line",
            symbol: "none",
            color: "rgba(216, 213, 213, 0.8)",
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: [],
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          },
          {
            name: "DEA",
            type: "line",
            symbol: "none",
            color: "rgba(214, 214, 100, 0.8)",
            xAxisIndex: 2,
            yAxisIndex: 2,
            data: [],
            showSymbol: false,
            sampling: "average",
            showAllSymbol: false
          }
        ]
      });
      //  缩放事件
      this.dataZoom();
    },
    // dataZoom缩放事件
    dataZoom() {
      let _this = this;
      charts.on("dataZoom", function(params) {
        let start = params.batch[0].start;
        _this.startLeft = params.batch[0].start;
        if (start == 0) {
          // 如果时间一样的话，不再发起请求。
          if (_this.startTime != _this.kData.times[0][0]) {
            _this.startTime = _this.kData.times[0][0] || "";
            _this.reqList(2);
          }
          params.batch[0].start = 10;
        }
      });
    },
    // 接口请求数据
    reqList(tag) {
      console.log("k线数据请求", tag);
      if (this.isReq) {
        this.isReq = false;
        if (tag == 1) {
          // this.loading = true;
          this.kData = {
            datas: [],
            times: [],
            vols: [],
            macds: [],
            difs: [],
            deas: []
          };
          this.mapData = [];
        }
        let param = {
          // k线请求的参数数据
        };
        if (tag == 2) {
          this.param.StartTime = this.kData.times[0][0] || "";
        }
        this.$api.cec
          .kChartsData(param)
          .then(res => {
            this.isReq = true;
            console.log("返回的数据", res);
            if (res.data.code == 200) {
              this.loading = false;
              if (res.data.data) {
                this.dataEmpty = false;
                let data = res.data.data;
                if (data.klinelist.length > 0 || this.kData.times.length != 0) {
                  this.mapData = data.klinelist.reverse();
                } else {
                  this.mapData = this.randomArr();
                }
                console.log("准备渲染的数据1", this.mapData);
              } else {
                this.dataEmpty = true;
                this.mapData = this.randomArr();
                console.log("准备渲染的数据2", this.mapData);
              }
              this.dealData();
            } else {
              this.dataEmpty = true;
            }
          })
          .catch(() => {
            this.isReq = true;
          });
      }
    },
    // 数据处理
    dealData() {
      var _this = this;
      if (this.mapData.length < 50 && this.mapData.length > 0) {
        console.log("数据处理1");
        this.mapData = this.createData(this.mapData).concat(this.mapData);
      }
      console.log("数据处理2");
      var datas = this.mapData.map(function(value) {
        return [
          value.openprice,
          value.closeprice,
          value.lowprice,
          value.heighprice
        ];
      });
      var times = this.mapData.map(function(value) {
        return [value.time];
      });
      var vols = this.mapData.map(function(value) {
        return value.count;
      });
      // difs
      var difs = this.mapData.map(function(value) {
        return value.diff;
      });
      // deas
      var deas = this.mapData.map(function(value) {
        return value.dea;
      });
      // macds
      var macds = this.mapData.map(function(value) {
        return value.macd;
      });
      // 重新组合数据
      this.kData.datas = datas.concat(this.kData.datas);
      this.kData.times = times.concat(this.kData.times);
      this.kData.vols = vols.concat(this.kData.vols);
      this.kData.difs = difs.concat(this.kData.difs);
      this.kData.deas = deas.concat(this.kData.deas);
      this.kData.macds = macds.concat(this.kData.macds);

      // 窗口显示数据的计算
      if (this.kData.times.length <= 200) {
        this.minData = 5;
        this.maxData = 60;
      } else if (this.kData.times.length <= 400) {
        this.minData = 3;
        this.maxData = 50;
      } else if (this.kData.times.length <= 600) {
        this.minData = 2;
        this.maxData = 40;
      } else if (this.kData.times.length <= 1000) {
        this.minData = 1;
        this.maxData = 30;
      } else if (this.kData.times.length <= 2000) {
        this.minData = 0.5;
        this.maxData = 10;
      } else if (this.kData.times.length <= 3000) {
        this.minData = 0.2;
      } else {
        this.minData = 0.1;
      }
      this.renderChart();
    },
    //如果接口数据没有请求过来，渲染一条当前时间的数据
    randomArr() {
      var myDate = new Date();
      myDate = myDate;
      var defaultArr = [
        {
          time: myDate,
          openprice: 0,
          closeprice: 0,
          lowprice: 0,
          heighprice: 0,
          count: 0,
          dea: 0,
          diff: 0,
          macd: 0
        }
      ];
      return defaultArr;
    },
    // 均线计算
    calculateMA(data, dayCount) {
      var result = [];
      for (var i = 0; i < data.datas.length; i++) {
        if (i < dayCount) {
          result.push("-");
          continue;
        }
        var sum = 0;
        for (var j = 0; j < dayCount; j++) {
          sum = this.$utils.add(sum, data.datas[i - j][1]);
        }
        result.push(this.$utils.div(sum, dayCount));
      }
      return result;
    },
    // 页面渲染
    renderChart() {
      var data = this.kData;
      let _this = this;
      charts.setOption(
        {
          xAxis: [
            {
              data: data.times,
              axisLabel: {
                //坐标轴刻度标签的相关设置。
                formatter: function(params) {
                  if (params.indexOf(":") == -1) {
                    return params;
                  }
                  if (
                    _this.choise == "km" ||
                    _this.choise == "k5m" ||
                    _this.choise == "k15m" ||
                    _this.choise == "k30m" ||
                    _this.choise == "time" ||
                    _this.choise == "k1h"
                  ) {
                    return _this.getMin(params);
                  } else if (_this.choise == "k1d") {
                    return _this.getDay(params);
                  } else if (_this.choise == "k1w") {
                    return _this.getDay(params);
                  } else {
                    return _this.getMonth(params);
                  }
                  return params;
                },
                color: "#C7CEE0" //坐标值的具体的颜色
              }
            },
            {
              data: data.times
            },
            {
              data: data.times
            }
          ],
          series: [
            {
              name: "this.choise",
              data: data.datas
            },
            {
              name: "MA5",
              data: this.calculateMA(data, 5)
            },
            {
              name: "MA10",
              data: this.calculateMA(data, 10)
            },
            {
              name: "MA30",
              data: this.calculateMA(data, 30)
            },
            {
              name: "MA60",
              data: this.calculateMA(data, 60)
            },
            {
              name: "Volumn",
              data: data.vols,
              itemStyle: {
                normal: {
                  color: function(params) {
                    var colorList;
                    if (
                      data.datas[params.dataIndex][1] >
                      data.datas[params.dataIndex][0]
                    ) {
                      colorList = "#12b886";
                    } else {
                      colorList = "#fa5252";
                    }
                    return colorList;
                  }
                }
              }
            },
            {
              name: "MACD",
              data: data.macds,
              itemStyle: {
                normal: {
                  color: function(params) {
                    var colorList;
                    if (params.data >= 0) {
                      colorList = "#12b886";
                    } else {
                      colorList = "#fa5252";
                    }
                    return colorList;
                  }
                }
              }
            },
            {
              name: "DIF",
              data: data.difs
            },
            {
              name: "DEA",
              data: data.deas
            }
          ],
          dataZoom: {
            minSpan: this.minData,
            maxData: this.maxData
          }
        },
        false,
        true
      );
    },
    // 时间分割函数，
    getYear(data) {
      if (data.indexOf(":") == -1) {
        return data;
      }
      let time = data.split(" ")[0];
      time = time.split("-");
      return time[0];
    },
    getMonth(data) {
      if (data.indexOf(":") == -1) {
        return data;
      }
      let time = data.split(" ")[0];
      time = time.split("-");
      return time[1] + "月";
    },
    getDay(data) {
      if (data.indexOf(":") == -1) {
        return data;
      }
      let time = data.split(" ")[0];
      time = time.split("-");
      return time[2];
    },
    getHour(data) {
      if (data.indexOf(":") == -1) {
        return data;
      }
      let time = data.split(" ")[1];
      time = time.split(":");
      return time[0];
    },
    getMin(data) {
      if (data.indexOf(":") == -1) {
        return data;
      }
      let time = data.split(" ")[1];
      time = time.split(":");
      return time[0] + ":" + time[1];
    },
    // 鼠标事件
    down() {
      this.startDown = true;
    },
    up() {
      // 鼠标弹起，判断是否加载数据
      if (this.startDown) {
        if (this.startLeft == 0) {
          this.startDown = false;
          if (this.startTime != this.kData.times[0][0]) {
            this.startTime = this.kData.times[0][0] || "";
            this.reqList(2);
          }
        }
      }
    },
    // 提示框处理事件
    dealTool(params) {
      let _this = this;
      params.forEach(el => {
        switch (el.seriesIndex) {
          case 0:
            _this.datas = {
              color: el.color,
              open: {
                name: "开",
                value: el.value[1]
              },
              close: {
                name: "收",
                value: el.value[2]
              },
              low: {
                name: "低",
                value: el.value[3]
              },
              heigh: {
                name: "高",
                value: el.value[4]
              }
            };
            break;
          case 1:
            _this.ma.ma5 = {
              name: "MA5",
              value: el.value,
              color: el.color
            };
            break;
          case 2:
            _this.ma.ma10 = {
              name: "MA10",
              value: el.value,
              color: el.color
            };
            break;
          case 3:
            _this.ma.ma30 = {
              name: "MA30",
              value: el.value,
              color: el.color
            };
            break;
          case 4:
            _this.ma.ma60 = {
              name: "MA60",
              value: el.value,
              color: el.color
            };
            break;
          case 5:
            _this.vol = {
              name: "成交量",
              value: el.value,
              color: el.color
            };
            break;
          case 6:
            _this.macd.macd = {
              name: "macd",
              value: el.value,
              color: el.color
            };
            break;
          case 7:
            _this.macd.dif = {
              name: "dif",
              value: el.value,
              color: el.color
            };
            break;
          case 8:
            _this.macd.dea = {
              name: "dea",
              value: el.value,
              color: el.color
            };
            break;
          default:
            break;
        }
      });
    }
  },

  computed: {},

  created() {
    this.reqList(1);
  },

  mounted() {
    this.createChart();
    window.onresize = function() {
      charts.resize();
    };
  },
  beforeDestroy() {
    charts.dispose();
    window.onresize = "";
  }
};
</script>
<style scoped>
.charts-box {
  position: relative;
  font-size: 13px;
  color: rgb(90, 104, 129);
}
.pos-box {
  position: absolute;
  left: 10px;
  z-index: 1;
  padding: 5px;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  -khtml-user-select: none;
  user-select: none;
}
.k-box {
  top: 5px;
}
.ma-box {
  left: 0px;
}
.vol-box {
  bottom: 20%;
}
.macd-box {
  bottom: 10%;
}
</style>
